package cn.com.ustudy.course.core.web.ctrl;

import cn.hutool.core.collection.CollectionUtil;
import cn.melonlib.cores.commons.comp.web.ctrl.BasicController;
import cn.melonlib.cores.commons.comp.web.ctrl.IndexController;
import cn.melonlib.cores.graphql.comp.web.bean.GraphqlArguments;
import cn.melonlib.cores.graphql.comp.web.proxy.GraphqlWebProxy;
import cn.melonlib.cores.graphql.comp.web.utils.GraphqlArgumentsUtils;
import cn.melonlib.graphql.cores.comp.engine.GraphqlEngine;
import cn.melonlib.objects.maps.JsonMap;
import graphql.ExecutionResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping(path = "/")
public class MainController extends BasicController {

    @Resource
    private GraphqlWebProxy graphqlWebProxy;


    @Resource
    private IndexController indexController;

    @Value("${server.servlet.context-path}")
    private String base;

    @Resource
    private GraphqlArgumentsUtils graphqlArgumentsUtils;

    @Resource
    private GraphqlEngine graphqlEngine;

    @CrossOrigin(originPatterns = "*")
    @ResponseBody
    @RequestMapping(value = "provider", method = {RequestMethod.POST}, produces = APPLICATION_JSON_UTF8_VALUE)
    public Object provider( HttpServletRequest request) throws Exception {
        graphqlArgumentsUtils.init(request);
        GraphqlArguments graphqlArguments=graphqlArgumentsUtils.getArguments();
        ExecutionResult executionResult=graphqlEngine.execute("GraphqlMetadata",graphqlArguments.getQuery(),graphqlArguments.getVariables());
        if(CollectionUtil.isNotEmpty(executionResult.getErrors())){
            return JsonMap.createMap().append("errors",executionResult.getErrors());
        }
        return JsonMap.createMap().append("data",executionResult.getData());
    }

    @GetMapping(value = "provider.api", produces = APPLICATION_JSON_UTF8_VALUE)
    public String providerApi(HttpServletRequest request, HttpServletResponse response)throws Exception{
        return graphqlWebProxy.providerMap(request,response);
    }



}
